package com.eeds.word;

import java.io.*;
import java.util.Map;
import java.util.Properties;

import freemarker.template.Configuration;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.commons.io.IOUtils;
import sun.misc.BASE64Encoder;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
public class WordUtil {



	// 资料 https://blog.csdn.net/itnoobie/article/details/46785549
	public static final Integer DOC = 0;
	public static final Integer DOT = 1;
	public static final Integer RTF = 6;
	public static final Integer TXT = 7;
	public static final Integer XML = 11;
	public static final Integer DOCM = 13;
	public static final Integer DOTX = 14;
	public static final Integer DOTM = 15;
	public static final Integer PDF = 17;
	/**
	 * @param filePath    word 源文件
	 * @param targetFile 转换后的文件
	 * @param type 类型
	 * @Description:
	 * @author Administrator
	 */
	public static void convert(String filePath, String targetFile,Integer type) {
		Dispatch doc = null;
		ActiveXComponent app = null;
		try {
			app = new ActiveXComponent("Word.Application"); //启动word
			app.setProperty("Visible", new Variant(false)); //为false时设置word不可见，为true时是可见要不然看不到Word打打开文件的过程
			Dispatch docs = app.getProperty("Documents").toDispatch();
			//打开编辑器
			doc = Dispatch.invoke(docs, "Open", Dispatch.Method, new Object[]{filePath, new Variant(false), new Variant(true)}, new int[1]).toDispatch(); //打开word文档
			Dispatch.call(doc, "SaveAs", targetFile, type);//xml文件格式宏11
			Dispatch.call(doc, "Close", false);
			app.invoke("Quit", 0);
			System.out.println("---------word转换完成--------");
			new File(filePath).delete();
		} catch (Exception e) {
			if(doc != null) {
				Dispatch.call(doc, "Close", false);
			}
			if(app != null) {
				app.invoke("Quit", 0);
			}
			throw new RuntimeException(e);
		}
	}

	/**
	 * @param dataMap
	 *            word中需要展示的动态数据，用map集合来保存
	 * @param templateName
	 *            word模板名称，例如：teample.ftl
	 * @param filePath
	 *            文件生成的目标路径，例如：D:/
	 */
	public static String createWord(Map dataMap, String templateName,String filePath) {
		try {


			//配置信息
			VelocityContext context = new VelocityContext(dataMap);

			//设置velocity资源加载器
			Properties prop = new Properties();
			prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
			Velocity.init(prop);


			//渲染模板
			StringWriter sw = new StringWriter();
			Template tpl = Velocity.getTemplate(templateName, "UTF-8");
			tpl.merge(context, sw);

			// 输出文件
			File outFile = new File(filePath + File.separator + System.currentTimeMillis()+".doc");

			// 如果输出目标文件夹不存在，则创建
			if (!outFile.getParentFile().exists()) {
				outFile.getParentFile().mkdirs();
			}
			FileOutputStream fileOutputStream = new FileOutputStream(outFile);
			try {
				//添加到zip
				IOUtils.write(sw.toString(), fileOutputStream, "UTF-8");
				IOUtils.closeQuietly(sw);
			} catch (IOException e) {
				throw new RuntimeException("失敗", e);
			}finally {
				fileOutputStream.close();
			}
			return outFile.getPath();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}

	}


	
	/**
	 * 将图片转换为BASE64为字符串
	 * @param filename
	 * @return
	 * @throws IOException
	 */
	public static String getImageString(String filename)  {
        InputStream in = null;  
        byte[] data = null;  
        try {  
            in = new FileInputStream(filename);  
            data = new byte[in.available()];  
            in.read(data);  
            in.close();  
        } catch (IOException e) {  
            throw new RuntimeException(e);
        } finally {
			try {
				if (in != null) {
					in.close();
				}
			}catch (Exception e){}
        }  
        BASE64Encoder encoder = new BASE64Encoder();
        return data != null ? encoder.encode(data) : "";  
   }

	/**
	 * 获取配置信息
	 */
	public static Configuration getConfig(){
			return new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS);
	}

}